package com.jdy.haoduoai;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.support.multidex.MultiDex;
import android.view.WindowManager;

import com.jdy.haoduoai.audioconverter.AndroidAudioConverter;
import com.jdy.haoduoai.audioconverter.callback.ILoadCallback;
import com.jdy.haoduoai.model.LeMachine;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.rx.util.async.Async;
import com.jdy.haoduoai.socket.SocketThreadManager;
import com.jdy.haoduoai.util.CustomConstants;
import com.jdy.haoduoai.util.FileManager;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.LePreference;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.widget.CustomOneBtnDialog;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.ycsj.goldmedalnewconcept.App;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.utils.GsonUtil;

import java.util.Map;

import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;

public class LeXiaoXiaoBanApp extends App {

  @SuppressWarnings("unused")
  private final boolean isDebug = false;

  public static LeXiaoXiaoBanApp instance;
  private static Context context;// static way to get context of this app!
  public static String ordernumber;
  public int  screenW, screenH;
  private int collectionId;
  private int orderId;
  private LeUser mLeUser;
  private LeMachine mLeBaby;
  private DisplayImageOptions options;
  private int growth_period;
  public String kidAge;

  private void removeTempFromPref() {
    SharedPreferences sp = getSharedPreferences(
        CustomConstants.APPLICATION_NAME, MODE_PRIVATE);
    sp.edit().remove(CustomConstants.PREF_TEMP_IMAGES).commit();
  }

  public Handler getmHandler() {
    return mHandler;
  }

  public void setmHandler(Handler mHandler) {
    this.mHandler = mHandler;
  }

  private Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {

      if (msg.what == -3) {
        Intent logoutIntent = new Intent("com.jdy.haoduoai.activity.logout");
        LeXiaoXiaoBanApp.getAppContext().sendBroadcast(logoutIntent);
        LeConfig.isLogin = false;
        LeConfig.isDeviceConnect = false;

        CustomOneBtnDialog.Builder cdb = new CustomOneBtnDialog.Builder(
                LeXiaoXiaoBanApp.getAppContext())
                .setTitle("下线通知")
                .setMessage("您的帐号已经在其它手机登录！如非本人操作，则密码可能已经泄露，建议修改密码后再重新登录。")
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                          @Override
                          public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();

                            SocketThreadManager.releaseInstance();

                          }
                        });
        final CustomOneBtnDialog cd = cdb.create();
        cd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        cd.setOnDismissListener(new DialogInterface.OnDismissListener() {
          @Override
          public void onDismiss(DialogInterface dialog) {
//            Intent toActivityIntent = new Intent(LeXiaoXiaoBanApp.getAppContext(), LoginActivity.class);
//            toActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
//                    | Intent.FLAG_ACTIVITY_CLEAR_TOP
//                    | Intent.FLAG_ACTIVITY_NEW_TASK);
//            LeXiaoXiaoBanApp.getAppContext().startActivity(
//                    toActivityIntent);
          }
        });
        cd.show();
      } else {
        Intent logoutIntent = new Intent("com.jdy.haoduoai.activity.logout");
        LeXiaoXiaoBanApp.getAppContext().sendBroadcast(logoutIntent);
        LeConfig.isLogin = false;
        LeConfig.isDeviceConnect = false;

        CustomOneBtnDialog.Builder cdb = new CustomOneBtnDialog.Builder(
                LeXiaoXiaoBanApp.getAppContext())
                .setTitle("下线通知")
                .setMessage("您有其他亲友正在连接控制小小班设备，请休息片刻。")
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                          @Override
                          public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                          }
                        });
        final CustomOneBtnDialog cd = cdb.create();
        cd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        cd.setOnDismissListener(new DialogInterface.OnDismissListener() {
          @Override
          public void onDismiss(DialogInterface dialog) {
//            Intent toActivityIntent = new Intent(LeXiaoXiaoBanApp.getAppContext(), LoginActivity.class);
//            toActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
//                    | Intent.FLAG_ACTIVITY_CLEAR_TOP
//                    | Intent.FLAG_ACTIVITY_NEW_TASK);
//            LeXiaoXiaoBanApp.getAppContext().startActivity(
//                    toActivityIntent);
          }
        });
        cd.show();
      }


    }
  };


  public int getGrowth_period() {
    return growth_period;
  }

  public void setGrowth_period(int growth_period) {
    this.growth_period = growth_period;
  }

  public DisplayImageOptions getDisplayImageOptions() {
    return options;
  }

  public int getCollectionId() {
    return collectionId;
  }

  public void setCollectionId(int collectionId) {
    this.collectionId = collectionId;
  }

  public int getOrderId() {
    return orderId;
  }

  public void setOrderId(int orderId) {
    this.orderId = orderId;
  }

  public static LeXiaoXiaoBanApp getInstance() {
    return instance;
  }

  public static Map<String, Object> globalMeta = null;

  private void readConfig() {

    Async.start(new Func0<String>() {

      @Override
      public String call() {

        byte[] data = FileManager.ReadDataFromAssetfile("meta_1.json");
        String json = new String(data);
        return json;

      }
    }).filter(new Func1<String, Boolean>() {

      @Override
      public Boolean call(String result) {
        return Tools.isNotEmpty(result);
      }
    }).subscribe(new Action1<String>() {
      @SuppressWarnings("unchecked")
      @Override
      public void call(String json) {
        if (Tools.isNotEmpty(json)) {
//          globalMeta = JsonSerializer.getInstance()
//              .deserialize(json, Map.class);
          globalMeta = GsonUtil.GsonToMaps(json, Map.class);
        }

      }
    });
  }

  @Override
  protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
  }

  @Override
  public void onCreate() {
    super.onCreate();

    //LeakCanary.install(this);

    LeXiaoXiaoBanApp.context = getApplicationContext();
    LePreference.getInstance().setContext(LeXiaoXiaoBanApp.context);
    instance = this;
    mLeUser = null;
    mLeBaby = null;

    LeConfig.PlayMode = LePreference.getInstance().getInt("playmode", 3);

    initImageLoader();
    readConfig();
    removeTempFromPref();
    // FFMpegService.getInstance().loadFFMpegBinary();

    AndroidAudioConverter.load(this, new ILoadCallback() {
      @Override
      public void onSuccess() {
        // Great!
      }
      @Override
      public void onFailure(Exception error) {
        // FFmpeg is not supported by device
        error.printStackTrace();
      }
    });
  }

  private void initImageLoader() {
    options = new DisplayImageOptions.Builder()
        .showImageOnFail(R.drawable.default_img_listitem) // 下载 失败 显示的 图片
        .cacheInMemory(true) // 缓存
        .bitmapConfig(Bitmap.Config.RGB_565) // 图片格式
        .build();
    ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(
        getApplicationContext()).writeDebugLogs().build();
    ImageLoader.getInstance().init(configuration);
  }

  public LeMachine getBaby() {
    return mLeBaby;
  }

  public LeUser getUser() {
    return mLeUser;
  }

  public void setUser(LeUser lu) {
    this.mLeUser = lu;
  }

  public void setBaby(LeMachine lb) {
    this.mLeBaby = lb;
  }

  public void forgetUser() {
    collectionId = 0;
    orderId = 0;
    this.mLeUser = null;
    SharedPreferences prefs = this.getSharedPreferences(Constant.USER_INFO,
        Context.MODE_PRIVATE);
    prefs.edit().clear().commit();

    LeConfig.isLogin = false;

    LePreference.getInstance().delete("usersig");
    LePreference.getInstance().delete("selectedpainpoint");
    LePreference.getInstance().delete("lastLaunchTime");

//    ImHelper ih = LeXiaoXiaoBanApp.getInstance().getImHelper();
//    if (ih != null) {
//      ih.logout();
//    }
  }

  public static Context getAppContext() {
    return LeXiaoXiaoBanApp.context;
  }

}
